<template>
	<div class="homepage" ref="homepage">
		<div class="backBtn" @click="back()" v-if="level != 1"></div>
		<div class="map" id="mapChartbank"></div>
	</div>
</template>

<script>
import cityMap from '@/js/china-main-city-map.js';
import * as echarts from 'echarts';
import areaJson from '@/assets/area.json';
import axios from 'axios';
// import positionImg from '@/assets/img/position.png';
import Vue from 'vue';
// import registerAndsetOption from '@/js/echarts-map'
import { bigScreenApi } from '@/api/index';
//中国地图（第一级地图）的ID、Name、Json数据
var chinaId = '100000';
var chinaName = '中国';
var chinaJson = null;

//记录父级ID、Name
var mapStack = [];
var parentId = null;
var parentName = null;

//Echarts地图全局变量，主要是在返回上级地图的方法中会用到
var myChart = null;
export default {
	name: 'chinaMap',
	props: {
		msg: String
	},
	data() {
		return {
			mapJson: {},
			chooseName: '',
			timeTitle: [],
			pointData: {},
			sum: {},
			mapData: {},
			cityId: '',
			alltree: [],
			mincount: 0,
			maxcount: 0
		};
	},
	props: {
		level: {
			type: [String, Number],
			default: 0
		}
	},
	mounted() {
		this.mapChartbank();
		// console.log(areaJson);
	},
	methods: {
		/**
		 * 返回上一级地图
		 */
		back() {
			if (mapStack.length != 0) {
				//如果有上级目录则执行
				var map = mapStack.pop();
				console.log(map, mapStack);
				axios.get('/json/map/' + map.mapId + '.json', {}).then(response => {
					const mapJson = response.data;
					this.mapJson = mapJson;
					//返回上一级后，父级的ID、Name随之改变
					parentId = map.mapId;
					parentName = map.mapName;
					this.cityId = map.mapId;
					this.chooseName = parentName;
					this.getMapData(myChart, map.mapId, map.mapName, mapJson, false);
					// this.registerAndsetOption(myChart, map.mapId, map.mapName, mapJson, false);
				});
			}
		},
		/**
		 * Echarts地图
		 */

		mapChartbank(divid) {
			let _this = this;
			axios.get('/json/map/' + chinaId + '.json', {}).then(response => {
				// console.log(response);
				const mapJson = response.data;
				this.mapJson = mapJson;
				myChart = echarts.init(document.getElementById('mapChartbank'));

				// console.log(myChart);
				// myChart.setOption(option);
				parentId = chinaId;
				parentName = '中国';
				this.chooseName = '中国';
				this.cityId = chinaId;
				this.getMapData();
				// this.registerAndsetOption(myChart, chinaId, chinaName, mapJson, false);
				myChart.on('click', function (param) {
					console.log(param);
					// if (param.componentSubType === 'effectScatter') {
					// todo...
					if (param.data) {
						_this.chooseEarea(param);
					}
					// }
				});
				//捕捉georoam事件，使下层的geo随着上层的geo一起缩放拖曳

				myChart.on('georoam', function (params) {
					_this.scaleMap(params);
				});
			});
		},
		scaleMap(params) {
			var option = myChart.getOption(); //获得option对象

			if (params.zoom != null && params.zoom != undefined) {
				//捕捉到缩放时

				option.geo[0].zoom = option.series[0].zoom + 0.1; //下层geo的缩放等级跟着上层的geo一起改变

				option.geo[0].center = option.series[0].center; //下层的geo的中心位置随着上层geo一起改变
			} else {
				//捕捉到拖曳时

				option.geo[0].center = option.series[0].center; //下层的geo的中心位置随着上层geo一起改变
			}

			myChart.setOption(option); //设置option
		},
		chooseEarea(param) {
			var cityId = cityMap[param.name];
			console.log(cityId);
			if (cityId) {
				//代表有下级地图
				axios.get('/json/map/' + cityId + '.json', {}).then(response => {
					const mapJson = response.data;
					this.mapJson = mapJson;
					this.chooseName = param.name;
					this.cityId = cityId;
					this.getMapData(myChart, cityId, param.name, mapJson, true);
					// console.log(this.chooseName);
					// console.log(mapJson);
				});
			} else {
				// let newId = null;
				// areaJson.forEach(item => {
				// 	if (item.name == param.name) {
				// 		newId = item.xzqhbm;
				// 	}
				// });
				// console.log(param.name, newId);
				// //代表有下级地图
				// axios.get('/json/map/' + newId + '.json', {}).then(response => {
				// 	const mapJson = response.data;
				// 	this.mapJson = mapJson;
				// 	this.chooseName = param.name;
				// this.getMapData(myChart, cityId, param.name, mapJson, true);
				// 	// console.log(this.chooseName);
				// 	// console.log(mapJson);
				// });
			}
		},
		/**
		 *
		 * @param {*} myChart
		 * @param {*} id        省市县Id
		 * @param {*} name      省市县名称
		 * @param {*} mapJson   地图Json数据
		 * @param {*} flag      是否往mapStack里添加parentId，parentName
		 */
		registerAndsetOption(myChart, id, name, mapJson, flag) {
			if (flag) {
				//往mapStack里添加parentId，parentName,返回上一级使用
				mapStack.push({
					mapId: parentId,
					mapName: parentName
				});
				parentId = id;
				parentName = name;
			}
			console.log('mapStack=================');
			this.$emit('mapCheck', { name: this.chooseName, mapJson: this.pointData, level: mapStack.length, cityId: parentId });
			// console.log(name, parentName);
			echarts.registerMap(name, this.mapJson);
			let options = {
				geo: {
					label: {
						normal: {
							show: false
						},
						emphasis: {
							show: false
						}
					},
					roam: true,
					opacity: 0,
					// zlevel: 1,
					map: name,
					// aspectScale: 0.75,
					zoom: 1,
					roam: true,
					z: 1,
					scaleLimit: {
						min: 1,
						max: 3
					},
					itemStyle: {
						normal: {
							areaColor: 'rgba(255,255,255,0)',
							shadowColor: 'rgba(255,255,255,0)',
							borderColor: 'rgba(255,255,255,0)',

							shadowOffsetX: 0,
							shadowOffsetY: 0
						}

						// center: this.mapJson.features ? this.mapJson.features[0].properties.cp : [],
					},
					emphasis: {
						itemStyle: {
							areaColor: 'rgba(255,255,255,0)',
							shadowColor: 'rgba(255,255,255,0)',
							borderColor: 'rgba(255,255,255,0)'
							//   label: {
							//     show: false,
							//   },
						}
					},
					center: parentName == '中国' ? [108.948024, 34.263161] : this.mapJson.features ? this.mapJson.features[0].properties.cp : []
				},
				visualMap: {
					min: 0,
					max: this.maxcount,
					text: ['High', 'Low'],
					realtime: false,
					calculable: true,
					inRange: {
						color: ['#92bbf9', '#5193f4', '#3175da']
					},
					show: true,
					textStyle: {
						color: '#fff'
					}
				},
				tooltip: {
					trigger: 'item',
					formatter: p => {
						// console.log(p);
						if (p.componentSubType == 'effectScatter') {
							let val = p.value;
							if (p.name == '南海诸岛') return;
							if (window.isNaN(val)) {
								val = 0;
							}
							// console.log(val, val.toFixed(2));
							let txtCon;
							if (val > 10000) {
								p.value instanceof Array
									? (txtCon =
											"<div style='text-align:left'>" +
											'<span  style="font-weight:600">' +
											p.name +
											'</span>' +
											':<br />农场总数：<span  style="color:#1a7b78 ">' +
											p.value[3] +
											'个</span>' +
											'</div>抵押牛只总数：<span  style="color:#1a7b78 ">' +
											p.value[4].toFixed(2) +
											'万头</span></div><br />' +
											'总授信金额<span  style="color:#1a7b78 ">' +
											p.value[5].toFixed(2) +
											'万元</span></div><br />' +
											'总用信金额<span  style="color:#1a7b78 ">' +
											p.value[6].toFixed(2) +
											'万元</span></div><br />' +
											'总评估金额<span  style="color:#1a7b78 ">' +
											p.value[7].toFixed(2) +
											'万元</span></div><br />' +
											'总抵押金额<span  style="color:#1a7b78 ">' +
											p.value[8].toFixed(2) +
											'万元</span></div><br />')
									: null;
							} else {
								p.value instanceof Array
									? (txtCon =
											"<div style='text-align:left'>" +
											'<span  style="font-weight:600">' +
											p.name +
											'</span>' +
											':<br />农场总数：<span  style="color:#1a7b78 ">' +
											p.value[3] +
											'个</span>' +
											'</div>抵押牛只总数：<span  style="color:#1a7b78 ">' +
											p.value[4] +
											'头</span></div><br />' +
											'总授信金额<span  style="color:#1a7b78 ">' +
											p.value[5].toFixed(2) +
											'万元</span></div><br />' +
											'总用信金额<span  style="color:#1a7b78 ">' +
											p.value[6].toFixed(2) +
											'万元</span></div><br />' +
											'总评估金额<span  style="color:#1a7b78 ">' +
											p.value[7].toFixed(2) +
											'万元</span></div><br />' +
											'总抵押金额<span  style="color:#1a7b78 ">' +
											p.value[8].toFixed(2) +
											'万元</span></div><br />')
									: null;
							}
							return txtCon;
						}
					},
					hideDelay: 10
				},
				series: []
			};
			this.timeTitle.forEach(item => {
				// var min = this.mapData[item][this.mapData[item].length - 1].value;
				// var max = this.mapData[item][0].value;
				// if (this.mapData[item].length === 1) {
				// 	min = 0;
				// }
				// console.log(options.options);
				options.series.push(
					{
						type: 'map',
						map: name,
						roam: true,
						selectedMode: false,
						zoom: 1,
						scaleLimit: {
							min: 1,
							max: 3
						},
						// geoIndex: 0,
						zlevel: 11,
						// z: 2,
						showLegendSymbol: false,
						label: {
							// 通常状态下的样式
							normal: {
								show: true,
								textStyle: {
									color: '#fff'
								}
							},
							// 鼠标放上去的样式
							emphasis: {
								textStyle: {
									color: '#640000'
								}
							}
						},
						tooltip: {
							show: false,
							formatter: function (params) {
								// console.log(params);
								return null;
							}
						},
						// tooltip: {
						//   trigger: 'item',
						//   formatter: (p) => {
						//     let val = p.value;
						//     if (p.name == '南海诸岛') return;
						//     if (window.isNaN(val)) {
						//       val = 0;
						//     }
						//     let txtCon =
						//       "<div style='text-align:left'>" + p.name + ':<br />牛只总数：' + val.toFixed(2) + '万</div>';
						//     return txtCon;
						//   },
						// },
						itemStyle: {
							normal: {
								borderColor: '#58c3ff',
								borderWidth: 1.5,
								areaColor: '#c5dcfe'
							}
						},
						emphasis: {
							label: {
								show: false
							},
							itemStyle: {
								areaColor: '#58c3ff'
							}
						},
						center: parentName == '中国' ? [108.948024, 34.263161] : this.mapJson.features ? this.mapJson.features[0].properties.cp : [],
						data: this.mapData[item]
					},
					{
						name: '散点',
						type: 'effectScatter',
						coordinateSystem: 'geo',
						// rippleEffect: {
						//   brushType: 'fill',
						// },
						// itemStyle: {
						//   normal: {
						//     color: '#F4E925',
						//     shadowBlur: 10,
						//     shadowColor: '#333',
						//   },
						// },
						// z: 1,
						zlevel: 12,
						data: this.pointData[item],
						symbol: 'image://' + require('@/assets/img/position.png'),
						symbolKeepAspect: true,
						// symbolSize: 8,
						symbolSize: [50, 80],
						showEffectOn: 'emphasis' //加载完毕显示特效
					}
				);
			});
			console.log(options);
			myChart = echarts.init(document.getElementById('mapChartbank'));
			myChart.setOption(options, true);
		},
		initMapData(mapJson) {
			var mapData = [];
			for (var i = 0; i < mapJson.features.length; i++) {
				mapData.push({
					name: mapJson.features[i].properties.name
					//id:mapJson.features[i].id
				});
			}
			return mapData;
		},
		// 生成随机数据
		getMapData(myChart, id, name, mapJson, flag) {
			let level = 1;
			// console.log('==========', this.cityId);
			if (this.cityId == '100000') {
				level = 1;
			} else if (this.cityId.includes('0000') && this.cityId != '100000') {
				level = 2;
			} else {
				level = 3;
			}

			this.$postAction(bigScreenApi.findMapCuapCount, {
				xzqhbm: level > 1 ? this.cityId : '',
				level: level
			})
				.then(res => {
					if (res && res.code == 1) {
						this.alltree = [...res.data];
						let maxcount = this.alltree.reduce((prev, current) => (Number(prev.useCost) > Number(current.useCost) ? prev : current));
						this.maxcount = Number(maxcount.useCost);
						// this.mincount = data.reduce((prev, current) => (Number(prev.useCost) < Number(current.useCost) ? prev : current));
						// console.log('===', this.alltree);
						this.timeTitle = ['data'];

						let pointData = {},
							mapJson = {},
							sum = {};
						for (let i = 0; i < this.timeTitle.length; i++) {
							mapJson[this.timeTitle[i]] = [];
							pointData[this.timeTitle[i]] = [];
							sum[this.timeTitle[i]] = 0;
							// console.log('===', this.mapJson.features, this.alltree);

							this.mapJson.features.forEach(father => {
								this.alltree.forEach(item => {
									// console.log('===', father.properties.name, item.xzqhmc);
									if (item.xzqhmc && item.xzqhmc.indexOf(father.properties.name) != -1) {
										mapJson[this.timeTitle[i]].push({
											name: father.properties.name,
											value: Number(item.useCost),
											cityCode: father.id ? father.id : ''
										});
										pointData[this.timeTitle[i]].push({
											name: father.properties.name,
											value: [
												father.properties.cp
													? father.properties.cp[0]
													: this.getCenterPoint(father.properties.name)
													? this.getCenterPoint(father.properties.name)[0]
													: father.geometry.coordinates[0][0][0][0],
												father.properties.cp
													? father.properties.cp[1]
													: this.getCenterPoint(father.properties.name)
													? this.getCenterPoint(father.properties.name)[1]
													: father.geometry.coordinates[0][0][0][1],
												item.xzqhmc,
												item.deptCount,
												item.pledgeCowCount || 0,
												Number(item.creditCost),
												Number(item.useCost),
												Number(item.assessCost),
												Number(item.pledgeCost)
											],
											cityCode: father.id ? father.id : ''
										});
									}
								});
							});
							mapJson[this.timeTitle[i]] = mapJson[this.timeTitle[i]].sort(function (a, b) {
								return b.value - a.value;
							});
						}
						this.mapData = mapJson;
						// this.sum = 0;
						this.pointData = pointData;
						this.registerAndsetOption(myChart, id, name, mapJson, flag);

						console.log(mapJson, sum, pointData);
					}
				})
				.finally(() => {
					// this.confirmLoading = false;
				});
		},
		getCenterPoint(name) {
			let point = [];
			areaJson.forEach(item => {
				if (item.name == name) {
					point = [item.lon, item.lat];
				}
			});
			return point;
		}
		// 获取经纬度
		// getLNGT(item) {
		//   let _this = this;
		//   let mapItem = {};
		//   AMap.plugin(['AMap.PlaceSearch'], function () {
		//     //构造地点查询类
		//     var placeSearch = new AMap.PlaceSearch({
		//       pageSize: 5, // 单页显示结果条数
		//       pageIndex: 1, // 页码

		//       citylimit: false, //是否强制限制在设置的城市内搜索
		//       // map: map, // 展现结果的地图实例
		//       // panel: 'panel', // 结果列表将在此容器中进行展示。
		//       // autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
		//     });
		//     //关键字查询
		//     placeSearch.search(item, function searchExamplePoint_cb(status, result) {
		//       console.log(result);
		//       if (status === 'complete') {
		//         mapItem = result.poiList.pois.map(({ name, location }) => ({
		//           name,
		//           longitude: location.lng,
		//           latitude: location.lat,
		//         }));
		//         console.log(JSON.stringify(mapItem[0]));
		//       } else {
		//         mapItem = [];
		//       }
		//     });
		//   });
		//   return mapItem;
		// },
	}
};
</script>

<style scoped lang="less">
.homepage {
	height: 100%;
	// overflow: auto;
	height: 100%;
	position: relative;
}

.map {
	width: 100%;
	height: 100%;
	background: transparent;
}
.backBtn {
	position: absolute;
	top: 0;

	cursor: pointer;
	z-index: 99;

	width: 1.13rem;
	height: 0.36rem;
	position: absolute;
	top: 0.12rem;
	left: 0.07rem;
	background: url(/img/dashboard/back.png) no-repeat;
	background-size: cover;
	&:hover,
	&:active {
		background-image: url(/img/dashboard/back-active.png);
	}
}
</style>
